package whiteboard

import (
	"fmt"
	"multimedia/utils"
	"net/http"
	"os"
	"sync"

	log "github.com/sirupsen/logrus"

	"github.com/gorilla/websocket"
)

type RecordConnSrv struct {
	UpGrader *websocket.Upgrader
	sync.RWMutex
}

func New() *RecordConnSrv {
	Upgrader := &websocket.Upgrader{
		ReadBufferSize:  1024 * 10,
		WriteBufferSize: 1024 * 10,
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}
	conn := &RecordConnSrv{
		UpGrader: Upgrader,
	}
	return conn
}

func (c *RecordConnSrv) HandleRequest(w http.ResponseWriter, r *http.Request, filename string) error {
	defer utils.HandlePanic()
	conn, err := c.UpGrader.Upgrade(w, r, nil)
	if err != nil {
		log.WithField("func:", " wsclient HandleRequest ").Errorf("ws connect error:%s,%v", filename, err)
		return nil
	}
	c.ReadMessage(conn, filename)
	return nil
}
func (c *RecordConnSrv) ReadMessage(conn *websocket.Conn, filename string) {
	conn.SetReadLimit(3145728)
	for {
		_, message, err := conn.ReadMessage()
		if err != nil {
			log.WithField("func", "websocket ReadMessage").Errorf("connect error")
			break
		}
		finePath := fmt.Sprintf("/data/apps/data/record_files/%s.webm", filename)
		file, err := os.OpenFile(finePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
		if err != nil {
			log.WithField("Func", "RecordWhite").Warnf("open file err %v,file is:%s", err, finePath)
			return
		}
		defer file.Close()
		a, e := file.Write(message)
		if e != nil {
			log.WithField("Func", "RecordWhite").Warnf("open file err %v,file is:%s", err, finePath)
			return
		}
		log.WithField("Func", "RecordWhite").Warnf("write len is:%d", a)
	}
}
